<?php

class NotificationInstall
{
	
	private $_config = array(
		'name' => 'notification',
		'title' => 'Notification module',
		'dependencies' => array(
			'editor',
			'languages' => array(
				'{{notification}}' => array(
					'fields' => array (
						'subject' => 'varchar(255) NOT NULL',
						'body' => 'text NOT NULL'
					)
				),
			),
		),
		'import' => array(
			'application.modules.notification.NotificationModule',
			'application.modules.notification.models.Notification',
		)
	);

	public function config()
	{
		return $this->_config;
	}
	
	public function install()
	{
		$languages = Languages::model()->getLanguages();

		foreach ($languages as $language)
		{
			foreach ($this->_config['dependencies']['languages']['{{notification}}']['fields'] as $field => $type)
			{
				$keys[] = $field.'_'.$language['code'];
				$values[] = ':'.$field.'_'.$language['code'];
				$fields[] = "`".$field."_".$language['code']."` ".$type.",";
			}
		}
		
		$sql = "DROP TABLE IF EXISTS {{notification}};";
		Yii::app()->db->createCommand($sql)->execute();

		$sql="
		CREATE TABLE IF NOT EXISTS {{notification}} (
		  `id` int(11) NOT NULL AUTO_INCREMENT,";
			$sql .= implode("", $fields);
			$sql .= "
		  `creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
		  PRIMARY KEY (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
		Yii::app()->db->createCommand($sql)->execute();

		$sql="INSERT INTO {{notification}} (".implode(', ', $keys).", creation_date) VALUES (".implode(', ', $values).", :creation_date);";
		$command = Yii::app()->db->createCommand($sql);

		foreach ($languages as $language)
		{
			$command->bindValue(":subject_".$language['code'], Yii::t('NotificationModule.install', 'Registration', array(), null, $language['code']), PDO::PARAM_STR);
			$command->bindValue(":body_".$language['code'], Yii::t('NotificationModule.install', '<p>Hello!</p><p>You have registered on site %sitename%.</p><p>Your login: %login% <br>Your password: %password%</p><p>Administration. <br></p>', array(), null, $language['code']), PDO::PARAM_STR);
		}
		$command->bindValue(":creation_date", "2012-03-16 01:53:00", PDO::PARAM_STR);
		$command->execute();
		
		foreach ($languages as $language)
		{
			$command->bindValue(":subject_".$language['code'], Yii::t('NotificationModule.install', 'New user registration', array(), null, $language['code']), PDO::PARAM_STR);
			$command->bindValue(":body_".$language['code'], Yii::t('NotificationModule.install', '<p>На сайте %sitename% только что зарегистрировался новый пользователь %username%.<br></p>', array(), null, $language['code']), PDO::PARAM_STR);
		}
		$command->bindValue(":creation_date", "2012-07-17 21:53:39", PDO::PARAM_STR);
		$command->execute();
		
	}

	public function uninstall()
	{
		Yii::app()->db->createCommand()->dropTable('{{notification}}');
	}
}